<?php
require_once 'Transaction\confirmAction.php';
require_once APPLICATION_PATH.'\misc\Additional.php';
require_once APPLICATION_PATH.'\misc\Paging.php';
require_once APPLICATION_PATH.'\misc\sessionController.php';
class TransactionController extends Zend_Controller_Action
{

    private $paramName = array(
        'Super',
        'admin'
        );

    private $item_per_page = null;

    public function init()
    {
        $this->item_per_page = Paging::$number;
    }

    public function addLog($message)
    {   
        $sessionController = new sessionController();
        $actionLog = new Application_Model_DbTable_Actionlog();
        $actionLog->addActionLog($sessionController->getSessionLogId(),"[".$_SERVER['REMOTE_ADDR']."][".$sessionController->getSessionUsername()."] $message");
    }
    
    public function checkAdminSession(){
        $sessionController=new sessionController();
        if($sessionController->checkSessionAdmin($this->paramName)){
            $this->view->sessioncontroller = $sessionController;
        }else{
            $this->_helper->redirector('login','admin');
        }
    }
    
    public function indexAction()
    {   
        $this->checkAdminSession();
        
        $title = "Rangkuman";
        $this->view->title = $title;
        $this->view->headTitle($title);

        $trans_db = new Application_Model_DbTable_Transaction();
        $this->view->status = $trans_db->countStatus();
    }

    public function acceptedAction()
    {   
        $this->checkAdminSession();
         
        $title = "Transaksi Belum/Sudah Dikirim";
        $this->view->title = $title;
        $this->view->headTitle($title);
        $this->view->message = $this->_helper->_flashMessenger->getMessages();

        // Process POST request
        if($this->getRequest()->isPost()){
            date_default_timezone_set("Asia/Jakarta");
            $trans_db = new Application_Model_DbTable_Transaction();
            $code = $this->getRequest()->getParam("transactionCode");

            // Transaction is canceled
            if($this->getRequest()->getParam("cancel")){
                if($this->getRequest()->getParam("statusId")==3) $newStatus = 8;
                else $newStatus = 9;

                $trans_db->updateStatus($this->getRequest()->getParam("transactionId"), $newStatus);
                $trans_db->insertReason($this->getRequest()->getParam("transactionId"), $this->getRequest()->getParam("reason"));
                $trans_db->lastUpdate($this->getRequest()->getParam("transactionId"), date("Y/m/d H:i:s"));

                // Log
                $this->addLog("Batalkan Transaksi: $code");

                // Message
                $this->_helper->_flashMessenger->addMessage("Transaksi $code telah dibatalkan");
                $this->_helper->redirector('accepted');
            }
        }
    }
    
    public function pendingAction()
    {
        $this->checkAdminSession();
        
        $title = "Transaksi Belum/Sudah Dibayar";
        $this->view->title = $title;
        $this->view->headTitle($title);
        $this->view->message = $this->_helper->_flashMessenger->getMessages();

        // Process POST request
        if($this->getRequest()->isPost()){
            date_default_timezone_set("Asia/Jakarta");
            $trans_db = new Application_Model_DbTable_Transaction();
            $code = $this->getRequest()->getParam("transactionCode");

            // Payment is accepted
            if($this->getRequest()->getParam("accept")){
                $trans_db->updateStatus($this->getRequest()->getParam("transactionId"), 3);
                $trans_db->lastUpdate($this->getRequest()->getParam("transactionId"), date("Y/m/d H:i:s"));
                
                // Generate PUK
                require_once 'Transaction\PukAction.php';
                $puk_gen = new PukAction();
                $puk = $puk_gen->pukCreator($this->getRequest()->getParam("transactionId"));
                
                // Send PUK to user email
                $trans = $trans_db->getTransaction($this->getRequest()->getParam("transactionId"));
                $buyer_db = new Application_Model_DbTable_Buyers();
                $buyer = $buyer_db->getBuyer($trans["buyer_id"]);
                
                $subject = "Persetujuan pembayaran transaksi ".$trans["code"]." dan PUK Anda";
                $body = 
                    "Yth. ".$buyer[name].",\n\n".
                    "Pembayaran Anda untuk transaksi ".$trans["code"]." telah kami konfirmasi dan setujui.\n\n".
                    "PUK Anda adalah $puk.".
                    "PUK ini akan diperlukan pada saat penyerahan barang oleh kurir kami. Kegagalan dalam memberikan PUK yang tepat akan menyababkan pembatalan serah terima barang.\n".
                    "Pastikan bahwa orang yang akan menerima barang Anda nanti mengetahui PUK ini apabila barang akan diterima oleh orang selain Anda.\n\n".
                    "Terima kasih karena telah berbelanja di BitzPlaza dan kami sangat senang berbisnis dengan Anda";
                $to = array($buyer["email"]=>$buyer["name"]);
                
                $additional = new Additional();
                $additional->sendEmail($body, $to, $subject);

                // Log
                $this->addLog("Setujui Pembayaran: $code");

                // Message
                $this->_helper->_flashMessenger->addMessage("Pembayaran untuk transaksi $code telah disetujui");
            }
            // Transaction is canceled or payment is rejected
            else if($this->getRequest()->getParam("cancel")){
                if($this->getRequest()->getParam("statusId")==1) $newStatus = 6;
                else $newStatus = 7;

                $trans_db->updateStatus($this->getRequest()->getParam("transactionId"), $newStatus);
                $trans_db->insertReason($this->getRequest()->getParam("transactionId"), $this->getRequest()->getParam("reason"));
                $trans_db->lastUpdate($this->getRequest()->getParam("transactionId"), date("Y/m/d H:i:s"));

                // Send rejection email
                $trans = $trans_db->getTransaction($this->getRequest()->getParam("transactionId"));
                $buyer_db = new Application_Model_DbTable_Buyers();
                $buyer = $buyer_db->getBuyer($trans["buyer_id"]);
                
                $subject = "Pembatalan transaksi ".$trans["code"];
                $body = 
                    "Yth. ".$buyer[name].",\n\n".
                    "Kami ingin menginformasikan bahwa transaksi Anda dengan kode ".$trans["code"]." telah dibatalkan.\n".
                    "Adapun alasan pembatalan tersebut adalah \"".$this->getRequest()->getParam("reason")."\".\n\n".
                    "Apabila Anda merasa ada kesalahan dalam pembatalan tersebut atau ingin memberikan klarifikasi, Anda dapat mengirimkan email ke pembayaran@bitzplaza.com\n\n".    
                    "Kami mohon maaf apabila ada ketidaknyamanan yang terjadi.";
                $to = array($buyer["email"]=>$buyer["name"]);
                
                $additional = new Additional();
                $additional->sendEmail($body, $to, $subject);
                
                // Log
                $this->addLog("Batalkan Transaksi: $code");

                // Message
                $this->_helper->_flashMessenger->addMessage("Transaksi $code telah dibatalkan");
            }

            $this->_helper->redirector('pending');
        }
    }
    
    public function canceledAction()
    {   
        $this->checkAdminSession();
        
        $title = "Transaksi yang dibatalkan/tidak diterima";
        $this->view->title = $title;
        $this->view->headTitle($title);

        // Process POST request
        if($this->getRequest()->isPost()){
            // Transaction is deleted
            if($this->getRequest()->getParam("delete")){
                $trans_db = new Application_Model_DbTable_Transaction();
                $trans_db->deleteTransaction($this->getRequest()->getParam("transactionId"));
            }
        }
    }
    
    public function receivedAction()
    {   
        $this->checkAdminSession();
        
        $title = "Transaksi Sudah Diterima";
        $this->view->title = $title;
        $this->view->headTitle($title);

        // Process POST request
        if($this->getRequest()->isPost()){
            // Transaction is deleted
            if($this->getRequest()->getParam("delete")){
                $trans_db = new Application_Model_DbTable_Transaction();
                $trans_db->deleteTransaction($this->getRequest()->getParam("transactionId"));
            }
        }
    }
    
    public function detailsAction()
    {   
        $this->checkAdminSession();
         
        $id = $this->_getParam('id', 0);
        if ($id > 0) {
            $trans_db = new Application_Model_DbTable_Transaction();
            $transaction = $trans_db->getTransaction($id);
			
            $this->view->transaction = $transaction;
			if($transaction["transaction_status_id"]==5) 
				$this->view->receiver = $trans_db->getReceiver($id);

            $title = "Transaksi: ".$transaction['code'];
            $this->view->title = $title;
            $this->view->headTitle($title);
        } else {
            $this->_helper->redirector('index');
        }
    }
    public function tableAction()
    {
        $this->_helper->layout()->disableLayout();

        if(!$this->getRequest()->isPost()){
            return;
        }

        // get date from request
        $date = $this->getRequest()->getParam("date");
        $dateCond = "";
        if($date){
            $dateArr = explode("-", $date);
            $tday = mktime(0,0,0,$dateArr[1],$dateArr[2],$dateArr[0]);
            $tmrw = $tday + (24*60*60);

            $today = date("Y/m/d H:i:s",$tday);
            $tomorrow = date("Y/m/d H:i:s",$tmrw);
            $dateCond = "last_update >= '$today' AND last_update < '$tomorrow' AND ";

            $order = "last_update";
        }

        // Parameter for database query
        $status = $this->getRequest()->getParam("statusId");
        $page = $this->getRequest()->getParam("page",1);
        $this->view->page = $page;
        $this->view->status = $status;
        $order = ($status < 5)?null:"last_update";

        $trans_db = new Application_Model_DbTable_Transaction();
        if($status <= 5){
            $this->view->data = $trans_db->getAll($this->item_per_page,$page,$dateCond."transaction_status_id = $status",$order);
        }else{
            $this->view->data = $trans_db->getAll($this->item_per_page,$page,$dateCond."transaction_status_id > 5",$order);
        }

        //table's navigator
        $paging = new Paging();
        if($status <= 5){
            $tpage = $paging->totalPages($trans_db->countRows($dateCond."transaction_status_id = $status"));
        }else{
            $tpage = $paging->totalPages($trans_db->countRows($dateCond."transaction_status_id > 5"));
        }
        if($tpage>1){
            $this->view->back = $paging->back("transaction","table",$page,$order,null);
            $this->view->current = $paging->current("transaction","table",$tpage,$page,$order,null)."/ $tpage";
            $this->view->next = $paging->next("transaction","table",$tpage,$page,$order,null);
        }
    }
    
    public function displayAction()
    {
       $this->_helper->layout->disableLayout();

       $sessionController=new sessionController();
       $transaction = new Application_Model_DbTable_Transaction();
       $receivers = new Application_Model_DbTable_Receiver();
       $transactionStatus = new Application_Model_DbTable_TransactionStatus();
       $additional = new Additional();
       $shop = new Application_Model_DbTable_Shop();
       $id = $this->_getParam('id', 0);
       $this->view->id=$id;
       if($sessionController->checkSessionBuyer()){
            $trans=$transaction->fetchRow('transaction_id='.(int)$id);
            $receiver=$receivers->fetchRow('transaction_id='.(int)$id);
            $status = $trans['transaction_status_id'];
            $statusDescrip=$transactionStatus->getDescription('status_id='.(int)$status);
            $code=$trans['code'];
            $shop_id=$trans['shop_id'];
            $shopRow = $shop->getShop($shop_id);
            $shop=$shopRow['name'];
            $date=$trans['date'];
            $transDate=$additional->monthConverter($date);
            $details=$trans['details'];
            $details=str_replace('-', '<br/>', $details);
            $total_payment=$trans['total_payment'];
            $receiverName = $receiver['name'];
            $receiverRelation = $receiver['relationship'];
            $receiver_address= $trans['receiver_address'];
            $cancel_reason = $trans['cancel_reason'];
            $delivery_date=$trans['delivery_date'];
            $payment_date=$trans['payment_date'];
            $receiver=$trans['receiver'];
            $receiver_address=$trans['receiver_address'];
            $receiver_city=$trans['receiver_city'];
            $receiver_province=$trans['receiver_province'];
            $receiver_zip=$trans['receiver_zip'];
            $s="<tr><td>Status </td><td>:</td><td>$statusDescrip</td></tr>";
            $a="<tr><td>Kode Transaksi</td><td>:</td><td>$code</td></tr>";
            $b="<tr><td>Nama Toko </td><td>:</td><td><a href=''>$shop</a></td></tr>";
            $c="<tr><td>Tanggal Pembelian </td><td>:</td><td>$transDate</td></tr>";
            $d="<tr><td>Rincian </td><td>:</td><td>$details</td></tr>";
            $e="<tr><td>Total Pembayaran </td><td>:</td><td>$total_payment</td></tr>";
            $g="<tr><td>Alamat Penerima </td><td>:</td><td>$receiver_address</td></tr>";
            $h="<tr><td>Alasan Pembatalan </td><td>:</td><td>$cancel_reason</td></tr>";
            $i="<tr><td>Tanggal Penerimaan </td><td>:</td><td>$delivery_date</td></tr>";
            $j="<tr><td>Tanggal Pembayaran </td><td>:</td><td>$payment_date</td></tr>";
            $k="<tr><td>Calon Penerima </td><td>:</td><td>$receiver</td></tr>";
            $l="<tr><td>Alamat Calon Penerima </td><td>:</td><td>$receiver_address</td></tr>";
            $m="<tr><td>Kota Calon Penerima </td><td>:</td><td>$receiver_city</td></tr>";
            $n="<tr><td>Provinsi Calon Penerima </td><td>:</td><td>$receiver_province</td></tr>";
            $o="<tr><td>Pos Kode Calon Penerima </td><td>:</td><td>$receiver_zip</td></tr>";
            $p="<tr><td>Penerima </td><td>:</td><td>$receiverName</td></tr>";
            $r="<tr><td>Hubungan Penerima dengan pembeli</td><td>:</td><td>$receiverRelation</td></tr>";
            $this->view->button=false;
            if($status=="1"){
                $this->view->output=$a.$s.$c.$b.$e.$d.$k.$l.$m.$n.$o;
                $this->view->button=true;
            }else if($status =="2" || $status=="3" || $status =="4"){
                $this->view->output=$a.$s.$j.$e.$c.$b.$d.$k.$l.$m.$n.$o;
               
                $this->view->image=true;
            }else if($status=="5"){
                $this->view->output=$a.$s.$j.$e.$c.$b.$d.$p.$r;
            }
            else if($status =="6" || $status =="8" || $status=="9"){
                $this->view->output=$a.$s.$h.$j.$e.$c.$b.$d;
            }else if($status=="7" ){
                $this->view->output=$a.$s.$h.$c.$b.$e.$d;
            }else if($status=="10"){
                 $this->view->output=$a.$s.$i.$h.$j.$e.$c.$b.$d;
            }
        }else{
            $this->_helper->redirector('index','FrontPage');
        
        }
    }
    public function confirmAction()
    {
       $this->_helper->layout->disableLayout();
        $sessionController=new sessionController();
        $this->view->sessioncontroller = $sessionController;
        $this->view->transactions = new Application_Model_DbTable_Transaction();
        /* Initialize action controller here */

        // action body
        $sessionController = new sessionController();
        $cat_db = new Application_Model_DbTable_Category();
        $this->view-> categories = $cat_db->fetchAll();
        if($sessionController->checkSessionBuyer()){
            $this->view->contentcontroller='FrontPage';
            $this->view->contentaction='afterlogin';
            $sessionController->setBuyer();
            $this->view->buyerId=$sessionController->getSessionId();
            $this->view->rightlabel = "Pembeli";
        }else{
            $this->view->contentcontroller='buyer';
            $this->view->contentaction='login';
            $this->view->buyerId=0;
            $this->view->rightlabel = "Login Pembeli";
        }

        $this->_helper->layout->setLayout('frontlayout');
       $id = $this->_getParam('id', 0);
       $sessionController=new sessionController();
       $transaction = new Application_Model_DbTable_Transaction();
       $confirmAction = new Application_Controllers_Transaction_confirmAction();
       $transactionStatus = new Application_Model_DbTable_TransactionStatus();
       $additional = new Additional();
       $shop = new Application_Model_DbTable_Shop();
        if($sessionController->checkSessionBuyer()){

        $trans=$transaction->fetchRow('transaction_id='.(int)$id);
            $status = $trans['transaction_status_id'];
            $statusDescrip=$transactionStatus->getDescription('status_id='.(int)$status);
            $code=$trans['code'];
            $shop_id=$trans['shop_id'];
            $shopRow = $shop->getShop($shop_id);
            $shop=$shopRow['name'];
            $date=$trans['date'];
            $transDate=$additional->monthConverter($date);
            $details=$trans['details'];
            $details=str_replace('-', '<br/>', $details);
            $total_payment=$trans['total_payment'];
            $s="<tr><td>Status </td><td>:</td><td>$statusDescrip</td></tr>";
            $a="<tr><td>Kode Transaksi</td><td>:</td><td>$code</td></tr>";
            $b="<tr><td>Nama Toko </td><td>:</td><td><a href=''>$shop</a></td></tr>";
            $c="<tr><td>Tanggal Pembelian </td><td>:</td><td>$transDate</td></tr>";
            $d="<tr><td>Rincian </td><td>:</td><td>$details</td></tr>";
            $e="<tr><td>Total Pembayaran </td><td>:</td><td>$total_payment</td></tr>";

            $this->view->output=$a.$s.$c.$b.$e.$d;
        $formDisplay=new Application_Form_Display();
        $form = new Application_Form_Transaction();

        $form->transaction_id->setValue((int)$id);
        $form->bukti->setLabel('Bukti Pembayaran');
        $form->bukti->addFilter('Rename', realpath('.').'\\images\transactions\\'
                 .$id.'.png', $form->bukti);
        $formDisplay->addElements(array($form->transaction_id,$form->bank,$form->akun,$form->bukti,$form->submit));
        $this->view->form=$formDisplay;
        if ($this->getRequest()->isPost()) {
         $formData = $this->getRequest()->getPost();
            if ($formDisplay->isValid($formData)) {
                if($confirmAction->preAction($formDisplay)){
                        $confirmAction->onAction($formDisplay);
                        $this->_helper->_flashMessenger->addMessage('Pengisian detail pembayaran berhasil,
                            mohon tunggu verifikasi dari admin bitz-plaza untuk proses selanjutnya');
                        $this->_helper->redirector('display-transaction','buyer');
                }else{
                  $this->view->errormessage=$actionBuyer->wrongMessage;
                  $formDisplay->populate($formData);
                }
            } else {
               $formDisplay->populate($formData);
         }
        }
        }else{
             $this->_helper->redirector('index','FrontPage');
        
    }
}
    public function confirmatransAction()
    {        date_default_timezone_set("Asia/Jakarta");
                    $this->_helper->layout->disableLayout();
        $sessionController=new sessionController();
        $this->view->sessioncontroller = $sessionController;
        $this->view->transactions = new Application_Model_DbTable_Transaction();
        /* Initialize action controller here */

        // action body
        $sessionController = new sessionController();
        $cat_db = new Application_Model_DbTable_Category();
        $this->view-> categories = $cat_db->fetchAll();
        if($sessionController->checkSessionBuyer()){
            $this->view->contentcontroller='FrontPage';
            $this->view->contentaction='afterlogin';
            $sessionController->setBuyer();
            $this->view->buyerId=$sessionController->getSessionId();
            $this->view->rightlabel = "Pembeli";
        }else{
            $this->view->contentcontroller='buyer';
            $this->view->contentaction='login';
            $this->view->buyerId=0;
            $this->view->rightlabel = "Login Pembeli";
        }

        $this->_helper->layout->setLayout('frontlayout');
             
             $shop = new Application_Model_DbTable_Shop();
             
             $transaction = new Application_Model_DbTable_Transaction();
             //$message=$this->_getParam('message', 0);
             $buyerid=$this->_getParam('buyer_id', 0);
             $shopid=$this->_getParam('shop_id',0);
             $details=$this->_getParam('details', 0);
             $total = $this->_getParam('total', 0);
             $theShop=$shop->fetchRow('shop_id='.$shopid);
             $this->view->buyerId=$buyerid;
             
             $details=str_replace('-', '<br/>', $details);
             $this->view->message = "Terima kasih telah berbelanja di ".$theShop->name ."<br>".
                                    "mohon isi detail penerima untuk melanjutkan transaksi";
             $formDisplay = new Application_Form_Receiver();
             $this->view->form=$formDisplay;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($formDisplay->isValid($formData)) {
            

             $timeStamp = mktime(date('H'),date('i'), date('s')
                            ,date('m'),date('d'),date('y'));
             $dob_disp1=strftime('%Y-%m-%d %H:%M:%S',$timeStamp);
             $date=strftime('%Y%m%d%H%M%S',$timeStamp);
             $name=$formDisplay->getValue('receiver_name');
             $address=$formDisplay->getValue('receiver_address');
             $zip=$formDisplay->getValue('receiver_zip');
             $city=$formDisplay->getValue('receiver_city');
             $province=$formDisplay->getValue('receiver_province');
             $code='2'.$buyerid.''.$date;
             $data=array(
             'receiver'=>$name,
             'receiver_address'=>$address,
             'receiver_zip'=>$zip,
             'receiver_city'=>$city,
             'receiver_province'=>$province,
             'code'=> $code,
             'date'=>$dob_disp1,
             'shop_id'=>$shopid,
             'buyer_id'=>$buyerid,
             'transaction_status_id'=>1,
             'details'=>$details,
             'total_payment'=>$total,
             'last_update'=>$dob_disp1
             );
              $transaction->insert($data);
              $this->view->done=true;
              $this->view->message ="Terima kasih telah berbelanja di ".$theShop->name." dengan detail transaksi <br />".
                        "<table>
                        <tr><td>Kode Transaksi<td></td>:</td><td>$code</td></tr>
                        <tr><td>Nama Toko</td><td>:</td><td>$theShop->name</td></tr>
                         <tr><td>Total Pembayaran</td><td>:</td><td>$total</td></tr>
                        <tr><td>Keterangan</td><td>:</td><td>$details</td></tr>
                       
                        <tr><td>Calon Pembeli</td><td>:</td><td>$name</td></tr>
                        <tr><td>Alamat Calon Pembeli</td><td>:</td><td>$address</td></tr>
                        <tr><td>Kota Calon Pembeli</td><td>:</td><td>$city</td></tr>
                      <tr><td>Provinsi Calon Pembeli</td><td>:</td><td>$province</td></tr>
                      <tr><td>Pos Kode Calon Pembeli</td><td>:</td><td>$zip</td></tr>
                        </table>".
                        "<br />mohon lakukan pembayaran ke account ".
                        "xxxxxxxxxxxxx sejumlah Rp.$total dan isi detail pembayaran pada halaman transaksi";
              
            } else {
               $formDisplay->populate($formData);
            }
        }
             
             // $_redirector = $this->_helper->getHelper("Redirector");
             // $_redirector->gotoUrl('/DummyWeb/checkOut.php?message='.$message);
    }


}